<?php

namespace app\common\lib;

use app\common\lib\Common;
use app\common\lib\file_operate\FileOperate;
use think\Config;
use think\Db;

class EntranceToken
{

    const ADDR = '/authorization/api_operate/entrance';

    /**
     * 获取token 不用穿参数 token有效期为7200秒，需要将token存储
     * @return [type] [description]
     */
    public static function getToken()
    {
        $FileOperate = new FileOperate();

        $super_login = Config::get('super_login');

        $super_login = base64_encode($super_login);

        $config = $FileOperate->readConfigFile('config', '0245513d32194cc' . $super_login . '.ini');

        $config = json_decode($config, true);

        if (empty($config) || !isset($config['entrance_token']) || !isset($config['past_time']) || $config['past_time'] < time()) {

            $dirs = APP_PATH . DS . 'common' . DS . 'config';

            $dir = scandir($dirs);
            
            foreach ($dir as $key => $value) {

                $info = pathinfo($value);

                $ext = $info['extension'];

                if ($ext == 'ini') {
                    try {
                        @unlink($dirs . DS . $value);

                    } catch (\Exception $e) {

                    }
                }
            }

            //重新获取token
            $token = (new EntranceToken)->requestToken('2020542105');

            $data = [
                'entrance_token' => base64_encode($token),
                'past_time'      => time() + 6500,
            ];

            //写入文件
            $FileOperate->writeConfigFile('config', '0245513d32194cc' . $super_login . '.ini', $data);

            return $token;

        } else {
            return base64_decode($config['entrance_token']);
        }
    }

    //清除token
    public static function clearToken()
    {
        $super_login = Config::get('super_login');

        $super_login = base64_encode($super_login);

        $fileName = '..' . DS . 'config' . DS . '0245513d32194cc' . $super_login . '.ini';

        if (file_exists($fileName)) {

            @unlink($fileName);
        }
    }

    /**
     * get url
     */
    public static function getUrl()
    {

        return Config::get('admin_module_config.api_host') . self::ADDR;

    }

    /**
     * 请求token
     */
    private function requestToken($type)
    {

        $comm = new Common;

        $postData = $this->getProof();

        $postData['param'] = ['type' => $type];

        $back = $comm->requestInterface(self::getUrl(), $postData);

        if (isset($back['status']) && $back['status'] != 'success') {

            throw new \Exception("获取token异常:" . $back['message'] . ', code:' . $back['code']);

        }

        return $back['data']['token'];

    }

    /**
     *
     */
    public static function active($type, $name, $pwd)
    {

        $comm = new Common;

        $postData = (new EntranceToken)->getProof($name, $pwd);

        $postData['param'] = ['type' => $type];

        $back = $comm->requestInterface(self::getUrl(), $postData);

        return $back;

    }

    /**
     * 获取凭证信息
     */
    private function getProof($name = '', $pwd = '')
    {

        $uid = $name . cmf_password($pwd);
        //获取超级管理员信息

        if (empty($name)) {

            $userinfo = $this->getUser();

            $name = $userinfo['super_login'];

            $password = $userinfo['password'];

            $uid = $name . $password;

        }

        $re = Config::get('sign_config');

        $appid = $re['appid'];

        $appsecret = $re['appsecret'];

        $num1 = mt_rand(0, 13);

        $num2 = mt_rand(17, 31);

        $numc = ($num1 < 10) ? str_pad($num1, 2, "0", STR_PAD_LEFT) : $num1;

        $key = $this->user_verify_encodeKey($appsecret, $name, $num1, $num2) . "$numc$num2";

        $proof['proof'] = [

            'appid' => $appid,

            'uid'   => md5($uid),

            'key'   => $key,

        ];

        return $proof;

    }

    /**
     * 获取超级账号信息
     * @return [type] [description]
     */
    private function getUser()
    {

        $super_login = Config::get('super_login');

        $super_admin = Db::name('company')->where('super_login', $super_login)->value('super_admin');

        $password = Db::name('user')->where('id', $super_admin)->value('user_pass');

        $da = [

            'super_login' => $super_login,

            'password'    => $password,

        ];

        return $da;

    }

    /**
     * 身份验证加密
     */
    public function user_verify_encodeKey($appsecret, $userName, $num1, $num2)
    {

        $numc = ($num1 < 10) ? str_pad($num1, 2, "0", STR_PAD_LEFT) : $num1;

        return substr(md5($appsecret . md5($userName) . $numc . $num2), $num1, $num2);

    }

}
